import {
  TableContainer,
  Table,
  Thead,
  Tr,
  Th,
  Tbody,
  Td,
  Heading,
  Box,
  useColorModeValue,
  Button,
  HStack,
  Text,
  Badge,
} from '@chakra-ui/react';
import { getEllipsisTxt } from 'utils/format';
import { useState, useEffect, useMemo } from 'react';
import { ChevronLeftIcon, ChevronRightIcon } from '@chakra-ui/icons';
import request from 'utils/request';

// 模拟交易数据接口
interface MockTransaction {
  hash: string;
  from: { checksum: string };
  to: { checksum: string };
  gasUsed: { toString: () => string };
  blockTimestamp: string;
  receiptStatus: number;
}

// 生成随机哈希
const generateRandomHash = () => {
  const chars = '0123456789abcdef';
  let hash = '0x';
  for (let i = 0; i < 64; i++) {
    hash += chars[Math.floor(Math.random() * chars.length)];
  }
  return hash;
};

// 生成随机地址
const generateRandomAddress = () => {
  const chars = '0123456789abcdef';
  let address = '0x';
  for (let i = 0; i < 40; i++) {
    address += chars[Math.floor(Math.random() * chars.length)];
  }
  return address;
};

// 生成模拟数据
const generateMockTransactions = (count: number): MockTransaction[] => {
  const transactions: MockTransaction[] = [];
  const now = new Date();

  for (let i = 0; i < count; i++) {
    const date = new Date(now.getTime() - Math.random() * 30 * 24 * 60 * 60 * 1000);
    transactions.push({
      hash: generateRandomHash(),
      from: { checksum: generateRandomAddress() },
      to: { checksum: generateRandomAddress() },
      gasUsed: { toString: () => Math.floor(Math.random() * 1000000).toString() },
      blockTimestamp: date.toISOString(),
      receiptStatus: Math.random() > 0.1 ? 1 : 0,
    });
  }

  return transactions.sort((a, b) => 
    new Date(b.blockTimestamp).getTime() - new Date(a.blockTimestamp).getTime()
  );
};

const ITEMS_PER_PAGE = 10;

const Transactions = () => {
  const hoverTrColor = useColorModeValue('gray.100', 'gray.700');
  const [transactions, setTransactions] = useState<MockTransaction[]>([]);
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    const mockData = generateMockTransactions(50);
    setTransactions(mockData);
    request.get('home/transactions')
  }, []);

  // 计算总页数
  const totalPages = Math.ceil(transactions.length / ITEMS_PER_PAGE);

  // 获取当前页的数据
  const currentTransactions = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    return transactions.slice(startIndex, startIndex + ITEMS_PER_PAGE);
  }, [transactions, currentPage]);

  // 页面导航处理
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // 生成页码数组
  const getPageNumbers = () => {
    const pageNumbers: number[] = [];
    const maxVisiblePages = 5;
    
    if (totalPages <= maxVisiblePages) {
      for (let i = 1; i <= totalPages; i++) {
        pageNumbers.push(i);
      }
    } else {
      let startPage = Math.max(1, currentPage - 2);
      const endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
      
      if (endPage - startPage < maxVisiblePages - 1) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
      }
      
      for (let i = startPage; i <= endPage; i++) {
        pageNumbers.push(i);
      }
    }
    
    return pageNumbers;
  };

  return (
    <>
      <Heading size="lg" marginBottom={6}>
        交易记录
      </Heading>
      {transactions?.length ? (
        <Box 
          borderWidth="1px" 
          borderColor={useColorModeValue('gray.200', 'gray.600')} 
          borderRadius="xl" 
          padding="24px 18px"
          bg={useColorModeValue('white', 'gray.800')}
          boxShadow="sm"
        >
          <TableContainer w={'full'}>
            <Table variant="simple">
              <Thead>
                <Tr>
                  <Th color={useColorModeValue('gray.700', 'gray.300')}>交易哈希</Th>
                  <Th color={useColorModeValue('gray.700', 'gray.300')}>发送方</Th>
                  <Th color={useColorModeValue('gray.700', 'gray.300')}>接收方</Th>
                  <Th color={useColorModeValue('gray.700', 'gray.300')}>Gas 消耗</Th>
                  <Th color={useColorModeValue('gray.700', 'gray.300')}>交易时间</Th>
                  <Th isNumeric color={useColorModeValue('gray.700', 'gray.300')}>状态</Th>
                </Tr>
              </Thead>
              <Tbody>
                {currentTransactions.map((tx, key) => (
                  <Tr 
                    key={key} 
                    _hover={{ bgColor: hoverTrColor }} 
                    cursor="pointer"
                    transition="all 0.2s"
                  >
                    <Td color={useColorModeValue('gray.700', 'gray.300')}>{getEllipsisTxt(tx.hash)}</Td>
                    <Td color={useColorModeValue('gray.700', 'gray.300')}>{getEllipsisTxt(tx.from.checksum)}</Td>
                    <Td color={useColorModeValue('gray.700', 'gray.300')}>{getEllipsisTxt(tx.to.checksum)}</Td>
                    <Td color={useColorModeValue('gray.700', 'gray.300')}>{tx.gasUsed.toString()}</Td>
                    <Td color={useColorModeValue('gray.700', 'gray.300')}>{new Date(tx.blockTimestamp).toLocaleString('zh-CN', {
                      year: 'numeric',
                      month: '2-digit',
                      day: '2-digit',
                      hour: '2-digit',
                      minute: '2-digit',
                      second: '2-digit',
                      hour12: false
                    })}</Td>
                    <Td isNumeric>
                      <Badge colorScheme={tx.receiptStatus === 1 ? 'green' : 'red'} px={2} py={1}>
                        {tx.receiptStatus === 1 ? '成功' : '失败'}
                      </Badge>
                    </Td>
                  </Tr>
                ))}
              </Tbody>
            </Table>
          </TableContainer>
          
          {/* 分页控件 */}
          <HStack spacing={2} justifyContent="center" mt={6}>
            <Button
              size="sm"
              onClick={() => handlePageChange(currentPage - 1)}
              isDisabled={currentPage === 1}
              leftIcon={<ChevronLeftIcon />}
              colorScheme="blue"
              _hover={{
                transform: 'translateY(-1px)',
                shadow: 'md'
              }}
              transition="all 0.2s"
            >
              上一页
            </Button>
            
            {getPageNumbers().map((page) => (
              <Button
                key={page}
                size="sm"
                variant={currentPage === page ? "solid" : "outline"}
                onClick={() => handlePageChange(page)}
                colorScheme={currentPage === page ? "blue" : "gray"}
                _hover={{
                  transform: 'translateY(-1px)',
                  shadow: 'md'
                }}
                transition="all 0.2s"
              >
                {page}
              </Button>
            ))}
            
            <Button
              size="sm"
              onClick={() => handlePageChange(currentPage + 1)}
              isDisabled={currentPage === totalPages}
              rightIcon={<ChevronRightIcon />}
              colorScheme="blue"
              _hover={{
                transform: 'translateY(-1px)',
                shadow: 'md'
              }}
              transition="all 0.2s"
            >
              下一页
            </Button>
            
            <Text ml={4} color={useColorModeValue('gray.600', 'gray.400')}>
              共 {totalPages} 页
            </Text>
          </HStack>
        </Box>
      ) : (
        <Box>正在加载交易数据...</Box>
      )}
    </>
  );
};

export default Transactions;
